const WebSocket = require('ws');
const http = require('http');
const express = require('express');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// 存储连接的客户端
const clients = new Map();

wss.on('connection', (ws, req) => {
  let userId = null;

  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);
      
      // 处理不同类型的消息
      switch (data.type) {
        case 'auth':
          // 用户认证，存储连接
          userId = data.userId;
          clients.set(userId, ws);
          console.log(`用户 ${userId} 已连接`);
          break;

        case 'chat':
          // 处理聊天消息
          if (!userId) {
            ws.send(JSON.stringify({ 
              type: 'error', 
              message: '未认证用户不能发送消息' 
            }));
            return;
          }

          const targetClient = clients.get(data.targetUserId);
          if (targetClient) {
            targetClient.send(JSON.stringify({
              type: 'chat',
              from: userId,
              message: data.message,
              timestamp: new Date().toISOString()
            }));
          } else {
            // 目标用户不在线，可以存储到数据库等
            console.log(`用户 ${data.targetUserId} 不在线`);
          }
          break;

        default:
          break;
      }
    } catch (err) {
      console.error('消息处理错误:', err);
    }
  });

  ws.on('close', () => {
    if (userId) {
      clients.delete(userId);
      console.log(`用户 ${userId} 已断开连接`);
    }
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});